package com.luanhj.framework.tenant.interceptor;

import com.luanhj.framework.tenant.TenantContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author luanhj
 * @date 2025/6/3 10:03
 * @description 拦截器识别租户 ID
 **/
@Component
public class TenantInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();

        // 放行上传接口
        if ("/common/upload".equals(uri)) {
            return true;
        }
        if (uri.startsWith("/profile/upload/"))
            return true;
        String tenantId = request.getHeader("X-Tenant-ID");
        if (tenantId == null || tenantId.isEmpty()) {
            throw new RuntimeException("Missing X-Tenant-ID header");
        }
        TenantContext.setTenantId(tenantId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        TenantContext.clear();
    }
}
